<script setup lang="ts" name="SelectStorage">
import { onMounted, reactive, ref, watch } from "vue";
import { GetShipBillStorageList } from "@/api/tally";
import router from "@/router";
import { type ConfigProviderThemeVars, showFailToast } from "vant";
import { useBillInfo } from "@/store/bill-info";
import YardMapV2 from "@/components/TallyType/YardMapV2.vue";
import type { StorageItem } from "@/utils/interface";

const themeVars: ConfigProviderThemeVars = {
  searchContentBackground: "#ffffff",
  searchPadding: "0px",
  buttonSmallHeight: "30px",
  buttonSmallPadding: "12px",
  buttonDefaultHeight: "35px",
  buttonIconSize: "10px"
};

onMounted(() => {
  getStorage();
});

const input = defineProps(["transportBillId", "positionId", "storageId", "positionInfo"]);
const emit = defineEmits(["isOpen", "selectedStorage"]);
const isSearching = ref(false);
const billInfoStore = useBillInfo();
const storageList = ref([] as Array<StorageItem>);
const selectedStorageItem = ref({} as StorageItem);
const showYard = ref(false);
const isEditMapStorage = ref({} as StorageItem);

const searchParams = reactive({
  spot: "",
  isLeft: false,
  isActive: true
});
billInfoStore.$subscribe(() => {
  getStorage();
});
function onBlur() {
  let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  if (scrollTop > 0) {
    document.documentElement.scrollTop = 0;
    document.body.scrollTop = 0;
  }
}
watch(
  () => input,
  () => {
    getStorage();
  },
  { immediate: true, deep: true }
);
function getStorage() {
  selectedStorageItem.value = {} as StorageItem;
  const params = {
    transportBillId: input.transportBillId,
    positionId: input.positionId,
    isLeft: searchParams.isLeft ? "Y" : "",
    isActive: searchParams.isActive ? "Y" : "N",
    spot: searchParams.spot
  };
  isSearching.value = true;
  GetShipBillStorageList(params)
    .then((res: any) => {
      console.log(res);
      storageList.value = [] as Array<StorageItem>;
      if (res.success && res.data.length > 0) {
        storageList.value = res.data;
        storageList.value.forEach(item => {
          item.isChecked = false;
          if (input.storageId !== "" && input.storageId === item.id) {
            item.isChecked = true;
            selectedStorageItem.value = item;
          }
        });
      }
      isSearching.value = false;
    })
    .catch(() => {
      isSearching.value = false;
    });
}
function reset() {
  searchParams.spot = "";
  searchParams.isActive = true;
  searchParams.isLeft = true;
  getStorage();
}

function chooseStorage(data: StorageItem) {
  storageList.value.forEach(item => {
    item.isChecked = false;
  });
  data.isChecked = true;
  selectedStorageItem.value = data;
}

function showMap(item: StorageItem) {
  isEditMapStorage.value = item;
  showYard.value = true;
}

const onSelectedArea = (e: any) => {
  console.log(e);
  showYard.value = false;
  isEditMapStorage.value.goodsPositionId = e.id;

  for (let i = 0; i < storageList.value.length; i++) {
    if (storageList.value[i].id === isEditMapStorage.value.id) {
      storageList.value[i].goodsPositionId = isEditMapStorage.value.goodsPositionId;
      isEditMapStorage.value = {} as StorageItem;
      break;
    }
  }
};

function returnRes() {
  if (!selectedStorageItem.value.id) {
    showFailToast("请选择一个货垛");
    return;
  }
  emit("selectedStorage", selectedStorageItem.value);
  showPop(false);
}

function showPop(show: boolean) {
  emit("isOpen", show);
}
</script>

<template>
  <div class="flex-col h-[full] p-[20px] w-full" style="background: #f6f6f6">
    <van-config-provider :theme-vars="themeVars">
      <div class="flex h-[30px] justify-between mb-[10px]">
        <div
          class="flex justify-center items-center h-full text-center text-base"
        >
          选择货垛
        </div>
        <div
          class="flex h-full justify-center items-center text-center text-base"
        >
          <div class="text-sky-500" @click="returnRes">确定</div>
        </div>
      </div>
      <div class="flex flex-col w-[100%] h-[40px]">
        <div class="flex w-[100%] h-full">
          <div class="flex w-[50%] items-center">
            <div class="relative">
              <van-search
                v-model="searchParams.spot"
                left-icon=""
                :autofocus="false"
                :clearable="false"
                shape="round"
                calss="relative"
                background="transparent"
                placeholder="请输入关键词"
              >
              </van-search>
              <div class="absolute" style="top: 5px; right: 5px">
                <div
                  @click="getStorage"
                  class="w-[60px] h-[25px] leading-[25px] text-white text-sm tracking-wide text-center rounded-3xl bg-gradient-to-r from-blue-500 to-cyan-500"
                >
                  搜索
                </div>
              </div>
            </div>
          </div>
          <div class="flex flex-1 justify-center items-center gap-2">
            <van-button
              class="h-[35px] flex"
              plain
              round
              @click="searchParams.isActive = !searchParams.isActive"
              v-if="!searchParams.isActive"
              >有效</van-button
            >
            <van-button
              class="h-[35px] flex"
              icon-position="right"
              icon="cross"
              plain
              round
              @click="searchParams.isActive = !searchParams.isActive"
              v-if="searchParams.isActive"
              type="primary"
              >有效</van-button
            >
          </div>
          <div class="flex flex-1 justify-center items-center gap-2">
            <van-button
              class="h-[35px] flex"
              plain
              round
              @click="searchParams.isLeft = !searchParams.isLeft"
              v-if="!searchParams.isLeft"
              >余货</van-button
            >
            <van-button
              class="h-[35px] flex"
              icon-position="right"
              icon="cross"
              plain
              round
              @click="searchParams.isLeft = !searchParams.isLeft"
              v-if="searchParams.isLeft"
              type="primary"
              >余货</van-button
            >
          </div>
        </div>
      </div>
      <van-empty
        v-if="!storageList || storageList.length <= 0"
        description="暂无数据"
      />
      <div
        v-if="storageList && storageList.length > 0"
        class="w-full max-h-[590px] mt-[10px] flex flex-col overflow-auto"
      >
        <div
          v-for="item in storageList"
          :key="item.id"
          :class="
            item.isChecked ? 'border-blue-400 border-solid border-[1px]' : ''
          "
          class="w-[95%] mx-auto my-[5px] p-[10px] flex-col h-auto rounded bg-white text-[13px] shadow"
          @click="chooseStorage(item)"
        >
          <div class="flex w-full h-auto">
            <div class="flex flex-1 justify-center items-center">
              <van-checkbox v-model="item.isChecked"></van-checkbox>
            </div>
            <div class="flex flex-col w-[85%] h-auto px-[10px] gap-1">
              <div class="flex">
                <div class="flex flex-1">
                  <span class="text-slate-400">件数：</span>{{ item.piece }}
                </div>
                <div class="flex flex-1">
                  <span class="text-slate-400">吨数：</span>{{ item.ton }}
                </div>
              </div>
              <div class="flex">
                <div class="flex flex-1">
                  <span class="text-slate-400">货场：</span
                  >{{ item.positionName }}
                </div>
                <div class="flex flex-1">
                  <span class="text-slate-400">货位：</span>{{ item.spot }}
                </div>
              </div>
              <div class="flex">
                <div class="flex flex-1">
                  <span class="text-slate-400">包装：</span
                  >{{ item.packageTypeName }}
                </div>
                <div class="flex flex-1">
                  <span class="text-slate-400">有效：</span
                  >{{ item.isActive === "Y" ? "是" : "否" }}
                </div>
              </div>
              <div class="flex" v-if="item.isChecked">
                <div class="flex flex-1">
                  <span class="text-blue-500" @click="showMap(item)">修改图形</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </van-config-provider>
    <yard-map-v2
      v-if="showYard"
      :positionInfo="{ code: selectedStorageItem.areaCode  }"
      :goodsPositionId="isEditMapStorage.goodsPositionId"
      @closeMap="showYard = false"
      @saved="onSelectedArea"
    ></yard-map-v2>
  </div>
</template>

<style scoped></style>
